package com.lanju.dao;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.lanju.entity.HouseTransferList;
import com.lanju.entity.HouseTransferListItem;



@Repository
public class HouseTransferListDao extends BaseDao<HouseTransferList,String> {

    private static final Log log = LogFactory.getLog(HouseTransferListDao.class);
    @Autowired
	SessionFactory sessionFactory;
    
    @PersistenceContext(unitName = "financialmarketingUnit")
    private EntityManager entityManager;

    public void persist(HouseTransferList transientInstance) {
        try {
            entityManager.persist(transientInstance);
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }

    public void remove(HouseTransferList persistentInstance) {
        try {
            entityManager.remove(persistentInstance);
        } catch (RuntimeException re) {
            log.error("remove failed", re);
            throw re;
        }
    }
    
    public void removeItem(String transferId){
    	  try {
    		  Session session = entityManager.unwrap(Session.class);
    		  StringBuffer sql = new StringBuffer();
    		  sql.append("delete from HouseTransferListItem where transferId='"+transferId+"'");
              this.sessionFactory.getCurrentSession().createQuery(sql.toString()).executeUpdate();
          } catch (RuntimeException re) {
              log.error("remove failed", re);
              throw re;
          }
    }

    public HouseTransferList merge(HouseTransferList detachedInstance) {
        try {
            HouseTransferList result = entityManager.merge(detachedInstance);
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public HouseTransferList getById(String  id) {
        try {
            HouseTransferList instance = entityManager.find(HouseTransferList.class, id);
            entityManager.close();
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
    
    public List<HouseTransferListItem> getItemById(String  id) {
        try {
        	StringBuffer sql= new StringBuffer();
        	sql.append(" from HouseTransferListItem order num desc ");
        	Query query= entityManager.createQuery(sql.toString());
            return query.getResultList();
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }
    
    public void delTransfer(HouseTransferList obj){
    	try {
    		this.sessionFactory.getCurrentSession().delete(obj);
//			StringBuffer sql = new StringBuffer();
//			sql.append(" delete from  HouseTransferList where transferId='"+id+"'");
//			this.sessionFactory.getCurrentSession().createQuery(sql.toString()).executeUpdate();
    	} catch (Exception e) {
			e.printStackTrace();
		}
    }

    /** 根据 参数获取  */
    @SuppressWarnings("unchecked")
	public HouseTransferList getByParam(HouseTransferList entity) {
        try {
        	StringBuffer sqld = new StringBuffer("from HouseTransferList  where 1=1 ");
        	if(!StringUtils.isEmpty(entity.getTransferId())){
	            sqld.append(" and transferId='"+entity.getTransferId()+"' ");
	         }
            if(!StringUtils.isEmpty(entity.getHouseId())){
	            sqld.append(" and houseId='"+entity.getHouseId()+"' ");
	         }
	         if(!StringUtils.isEmpty(entity.getTransferType() )){
	             sqld.append(" and transferType ='"+entity.getTransferType()+"' ");
	         }
	         if(!StringUtils.isEmpty(entity.getListType() )){
	             sqld.append(" and listType ='"+entity.getListType()+"' ");
	         }
		     sqld.append(" order by createTime desc ");
	        Query query = entityManager.createQuery(sqld.toString());         
            List<HouseTransferList> list = query.getResultList();
            if(list!=null && list.size()>0){
                return list.get(0);
            }else{
                return null;
            }
        } catch (Exception e) {
            log.error("findByParam fail",e);
            throw e;
        }
    }
        

    @SuppressWarnings("unchecked")
	public List<HouseTransferList> getList(Map param, int pageSize, int offset) {
    	String transferType = (String) param.get("transferType");  //交接类型   0:租客交接清单 1:业主交接清单
    	String listType = (String) param.get("listType");  //0:软设备清单   1:硬件设备清单
    	String userId = param.get("userId").toString();
		StringBuffer sql = new StringBuffer(
		        "select a.*, h.houseName, h.address "
		                +" from lj_transfer_list a " 
		                +" join lj_house h on a.houseId = h.houseId");
		if (transferType != null  && param.get("transferType").toString().length()>0) {
			sql.append(" and a.transferType ="+ param.get("transferType").toString() );
		}
		if (listType != null  && listType.length()>0) {
			sql.append(" and a.listType ="+ listType );
		}
		if( userId != null && userId.length()>0){
			sql.append(" and  a.userId='"+userId+"' " );	//当前登录用户
		}
		
		sql.append(" order by a.createTime desc ");
		SQLQuery query = this.getSessionFactory().getCurrentSession().createSQLQuery(sql.toString());
        return query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).setFirstResult(offset).setMaxResults(pageSize).list();
    }
    
    
    public long getListCount(Map param) {
        try {
        	String transferType = (String) param.get("transferType");  //交接类型   0:租客交接清单 1:业主交接清单
        	String listType = (String) param.get("listType");  //0:软设备清单   1:硬件设备清单
        	String userId = param.get("userId").toString();
    		StringBuffer sql = new StringBuffer(
    		        "select a.*, h.houseName, h.address "
    		                +" from lj_transfer_list a " 
    		                +" join lj_house h on a.houseId = h.houseId");
    		if (transferType != null  && param.get("transferType").toString().length()>0) {
    			sql.append(" and a.transferType ="+ param.get("transferType").toString() );
    		}
    		if (listType != null  && listType.length()>0) {
    			sql.append(" and a.listType ="+ listType );
    		}
    		if( userId != null && userId.length()>0){
    			sql.append(" and  a.userId='"+userId+"' " );	//当前登录用户
    		}
    		SQLQuery query = this.getSessionFactory().getCurrentSession().createSQLQuery(sql.toString());
            return query.list().size();
           // return (long) query.getSingleResult();
        } catch (Exception e) {
            log.error("getList fail",e);
        }
        return 0;
    }


    @SuppressWarnings("unchecked")
	public List<Map> getBaseItemList(Map param) {
        StringBuffer sql = new StringBuffer(
        		 "select * "
        		+ "from lj_list_item_info  where 1=1 ");
        if(param.get("type")!=null){
        	sql.append(" and type = "+ param.get("type").toString() +" ");
        }
        sql.append(" order by num asc ");
    	SQLQuery query = this.getSessionFactory().getCurrentSession().createSQLQuery(sql.toString());
        return query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
    }
    

    
    /**
     * 获取房子列表 (供创建清单时选择房子)
     * */
	public List<Map> getHouseList(Map<String, Object> param) {
		   try {
			   StringBuffer sql = new StringBuffer("select h.*  from lj_house h   where 1=1 ");
			   if(param.containsKey("status")){
				   sql.append(" and h.status = "+ param.get("status").toString());
			   }
			   if(param.containsKey("userId")){
				   sql.append(" and h.userId = '"+ param.get("userId").toString()+"'");
			   }
			   //join lj_agreement a on a.houseId = h.houseId  and a.agreementType = 1  and a.status = 1
			   sql.append(" order by h.createTime desc") ;			   
			   SQLQuery query  = this.getSessionFactory().getCurrentSession().createSQLQuery(sql.toString());	           
			   return query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
	        } catch (Exception e) {
	            log.error("queryHouseList fail",e);
	        }
	        return null;
	}
	
}
